package com.whalehearing.tingyou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whalehearing.tingyou.domain.*;
import com.whalehearing.tingyou.dto.HearingAudiogramDTO;
import com.whalehearing.tingyou.dto.HearingImgDTO;
import com.whalehearing.tingyou.dto.HearingImgValueDTO;
import com.whalehearing.tingyou.mapper.HearingAudiogramMapper;
import com.whalehearing.tingyou.mapper.HearingImgMapper;
import com.whalehearing.tingyou.mapper.HearingImgValueMapper;
import com.whalehearing.tingyou.mapper.HearingInitialValuationMapper;
import com.whalehearing.tingyou.service.IHearingAudiogramService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 听力档案Service业务层处理
 *
 * @author zengjun-qxm
 * @date 2024-09-13
 */
@Service
public class HearingAudiogramServiceImpl extends ServiceImpl<HearingAudiogramMapper, HearingAudiogram> implements IHearingAudiogramService {

    private static final Logger log = LoggerFactory.getLogger(HearingAudiogramServiceImpl.class);
    @Autowired
    private HearingAudiogramMapper hearingAudiogramMapper;

    @Autowired
    private HearingInitialValuationMapper hearingInitialValuationMapper;

    @Autowired
    private HearingImgMapper hearingImgMapper;

    @Autowired
    private HearingImgValueMapper hearingImgValueMapper;

    /**
     * 查询听力档案列表
     *
     * @param hearingAudiogram 听力档案
     * @return 听力档案
     */
    @Override
    public List<HearingAudiogram> selectHearingAudiogramList(HearingAudiogram hearingAudiogram) {
        List<HearingAudiogram> hearingAudiogramList = hearingAudiogramMapper.selectList(buildQueryWrapper(hearingAudiogram));
        return hearingAudiogramList;
    }


    private LambdaQueryWrapper<HearingAudiogram> buildQueryWrapper(HearingAudiogram query) {
        Map<String, Object> params = query.getParams();
        LambdaQueryWrapper<HearingAudiogram> lqw = Wrappers.lambdaQuery();
        lqw.eq(query.getInitialValuationId() != null, HearingAudiogram::getInitialValuationId, query.getInitialValuationId());
        lqw.eq(query.getUserId() != null, HearingAudiogram::getUserId, query.getUserId());
        lqw.eq(query.getTestType() != null, HearingAudiogram::getTestType, query.getTestType());
        lqw.orderByDesc(HearingAudiogram::getCreateTime);
        return lqw;
    }


    /**
     * 新增听力档案对象
     */
    @Override
    public Long saveAudiogram(HearingAudiogramDTO hearingAudiogramDTO) {
        // 保存HearingAudiogram数据
        HearingAudiogram hearingAudiogram = new HearingAudiogram();
        hearingAudiogram.setInitialValuationId(hearingAudiogramDTO.getInitialValuationId());
        hearingAudiogram.setUserId(hearingAudiogramDTO.getUserId());
        hearingAudiogram.setTestType(hearingAudiogramDTO.getTestType());
        hearingAudiogramMapper.insert(hearingAudiogram);

        // 保存HearingImg数据
        for (HearingImgDTO hearingImgDTO : hearingAudiogramDTO.getHearingImgList()) {
            HearingImg hearingImg = new HearingImg();
            hearingImg.setAudiogramId(hearingAudiogram.getAudiogramId());
            hearingImg.setTestSubject(hearingImgDTO.getTestSubject());
            hearingImg.setHearingRating(hearingImgDTO.getHearingRating());
            hearingImg.setAiDetectionOpinion(hearingImgDTO.getAiDetectionOpinion());
            hearingImgMapper.insert(hearingImg);

            // 保存HearingImgValue数据
            for (HearingImgValueDTO hearingImgValueDTO : hearingImgDTO.getHearingImgValueList()) {
                HearingImgValue hearingImgValue = new HearingImgValue();
                hearingImgValue.setHearingImgId(hearingImg.getHearingImgId());
                hearingImgValue.setTestMethod(hearingImgValueDTO.getTestMethod());
                hearingImgValue.setFrequency(hearingImgValueDTO.getFrequency());
                hearingImgValue.setDecibelLevel(hearingImgValueDTO.getDecibelLevel());
                hearingImgValueMapper.insert(hearingImgValue);
            }
        }

        //返回主键听力档案主键id
        hearingAudiogramDTO.setAudiogramId(hearingAudiogram.getAudiogramId());
        return hearingAudiogramDTO.getAudiogramId();
    }


    /**
     * 根据用户ID查询用户名 - 用于听力检测首页展示
     */
    @Override
    public List<Map<String, Object>> getUserNameByUserId(Long userId) {
        // 通过用户ID查询听力档案表，关联查询用户昵称和创建时间
        List<HearingAudiogram> hearingAudiograms = hearingAudiogramMapper.selectList(
                new QueryWrapper<HearingAudiogram>().eq("user_id", userId));

        // 如果没有数据，直接返回空列表，避免后续处理
        if (hearingAudiograms.isEmpty()) {
            return Collections.emptyList();
        }

        // 循环查询HearingInitialValuation对象，设置nickName和createTime
        hearingAudiograms.forEach(hearingAudiogram -> {
            HearingInitialValuation hearingInitialValuation = hearingInitialValuationMapper.selectById(hearingAudiogram.getInitialValuationId());
            if (hearingInitialValuation != null) {
                hearingAudiogram.setNickName(hearingInitialValuation.getNickName());
            }
        });

        // 按 createTime 降序排序，并只返回最新三条数据
        return hearingAudiograms.stream()
                // 确保createTime不为空
                .filter(audiogram -> audiogram.getCreateTime() != null)
                .sorted(Comparator.comparing(HearingAudiogram::getCreateTime).reversed())
                .limit(3)
                .map(audiogram -> {
                    Map<String, Object> result = new HashMap<>();
                    result.put("nickName", audiogram.getNickName());
                    result.put("createTime", audiogram.getCreateTime());
                    return result;
                })
                .collect(Collectors.toList());
    }


    /**
     * 根据用户ID查询听力档案列表
     *
     * @param userId 用户ID
     * @return 听力档案列表，每个档案包含昵称和听力档案ID
     */
    @Override
    public List<Map<String, Object>> getAudiogramListByUserId(Long userId) {
        // 初始化结果列表
        List<Map<String, Object>> resultList = new ArrayList<>();

        // 构建查询条件，筛选指定用户ID的听力档案
        QueryWrapper<HearingAudiogram> wrapper = new QueryWrapper<HearingAudiogram>()
                .eq("user_id", userId);
        // 执行查询，获取所有符合条件的听力档案
        List<HearingAudiogram> hearingAudiograms = hearingAudiogramMapper.selectList(wrapper);

        // 遍历所有听力档案，构建需要返回的列表
        for (HearingAudiogram hearingAudiogram : hearingAudiograms) {
            // 初始化当前听力档案的映射对象
            Map<String, Object> currentEntry = new HashMap<>();

            // 构建初始评估信息的查询条件，用于获取昵称
            QueryWrapper<HearingInitialValuation> initialValuation = new QueryWrapper<HearingInitialValuation>()
                    .select("nick_name")
                    .eq("initial_valuation_id", hearingAudiogram.getInitialValuationId());
            // 根据查询条件获取初始评估信息
            HearingInitialValuation hearingInitialValuation = hearingInitialValuationMapper.selectOne(initialValuation);

            // 如果找到对应的初始评估信息，则添加昵称到当前条目中
            if (hearingInitialValuation != null) {
                currentEntry.put("nickName", hearingInitialValuation.getNickName());
            } else {
                // 如果没有找到对应的初始评估信息，昵称字段设置为null
                // 或者可以设置一个默认值
                currentEntry.put("nickName", null);
            }

            // 将当前听力档案的ID添加到当前条目中
            currentEntry.put("audiogramId", hearingAudiogram.getAudiogramId());
            currentEntry.put("createTime", hearingAudiogram.getCreateTime());
            // 将当前条目添加到结果列表中
            resultList.add(currentEntry);
        }
        // 按 createTime 降序排序
        resultList.sort(Comparator.comparing(
                entry -> (Date) entry.get("createTime"), Comparator.reverseOrder()));

        // 返回排序后的结果列表
        return resultList;
    }


    /**
     * 根据听力档案ID获取听力档案信息
     * 该方法首先查询听力档案基本信息，然后关联查询【测前初评】中的部分信息和【听力图】中的相关信息
     * 最后将查询到的信息封装成 HearingAudiogramDTO 对象返回
     *
     * @param audiogramId 听力档案ID
     * @return 返回封装了听力档案信息的 HearingAudiogramDTO 对象，如果没有找到对应信息则返回null
     */
    @Override
    public HearingAudiogramDTO getAudiogramInfoByAudiogramId(Long audiogramId) {
        // 查询听力档案信息
        HearingAudiogram hearingAudiogram = hearingAudiogramMapper.selectOne(
                new QueryWrapper<HearingAudiogram>().eq("audiogram_id", audiogramId));

        // 如果没有找到对应的听力档案信息，直接返回null
        if (hearingAudiogram == null) {
            return null;
        }

        // 创建DTO对象用于封装返回数据
        HearingAudiogramDTO hearingAudiogramDTO = new HearingAudiogramDTO();
        hearingAudiogramDTO.setAudiogramId(hearingAudiogram.getAudiogramId());
        hearingAudiogramDTO.setUserId(hearingAudiogram.getUserId());
        hearingAudiogramDTO.setTestType(hearingAudiogram.getTestType());
        hearingAudiogramDTO.setInitialValuationId(hearingAudiogram.getInitialValuationId());
        // 创建时间
        hearingAudiogramDTO.setCreateTime(hearingAudiogram.getCreateTime());

        // 获取【测前初评】中的，昵称，年龄区间
        HearingInitialValuation hearingInitialValuation = hearingInitialValuationMapper.selectOne(
                new QueryWrapper<HearingInitialValuation>()
                        .select("nick_name", "age_range")
                        .eq("initial_valuation_id", hearingAudiogram.getInitialValuationId()));
        if (hearingInitialValuation != null) {
            hearingAudiogramDTO.setNickName(hearingInitialValuation.getNickName());
            hearingAudiogramDTO.setAgeRange(hearingInitialValuation.getAgeRange());
        }

        // 获取【听力图】中的，检测对象，听力评级，AI检测意见
        List<HearingImg> hearingImgList = hearingImgMapper.selectList(
                new QueryWrapper<HearingImg>()
                        .select("hearing_img_id", "test_subject", "hearing_rating", "ai_detection_opinion")
                        .eq("audiogram_id", audiogramId));

        if (!hearingImgList.isEmpty()) {
            List<HearingImgDTO> hearingImgDTOList = new ArrayList<>();
            for (HearingImg hearingImg : hearingImgList) {
                HearingImgDTO hearingImgDTO = new HearingImgDTO();
                hearingImgDTO.setHearingImgId(hearingImg.getHearingImgId());
                hearingImgDTO.setTestSubject(hearingImg.getTestSubject());
                hearingImgDTO.setHearingRating(hearingImg.getHearingRating());
                hearingImgDTO.setAiDetectionOpinion(hearingImg.getAiDetectionOpinion());

                // 查询听力图中的听力值
                List<HearingImgValue> hearingImgValueList = hearingImgValueMapper.selectList(
                        new QueryWrapper<HearingImgValue>()
                                .select("test_method", "frequency", "decibel_level")
                                .eq("hearing_img_id", hearingImg.getHearingImgId()));

                if (!hearingImgValueList.isEmpty()) {
                    List<HearingImgValueDTO> hearingImgValueDTOList = new ArrayList<>();
                    for (HearingImgValue hearingImgValue : hearingImgValueList) {
                        HearingImgValueDTO hearingImgValueDTO = new HearingImgValueDTO();
                        hearingImgValueDTO.setTestMethod(hearingImgValue.getTestMethod());
                        hearingImgValueDTO.setFrequency(hearingImgValue.getFrequency());
                        hearingImgValueDTO.setDecibelLevel(hearingImgValue.getDecibelLevel());
                        hearingImgValueDTOList.add(hearingImgValueDTO);
                    }
                    hearingImgDTO.setHearingImgValueList(hearingImgValueDTOList);
                }
                hearingImgDTOList.add(hearingImgDTO);
            }
            hearingAudiogramDTO.setHearingImgList(hearingImgDTOList);
        }

        // 返回封装好的听力档案信息
        return hearingAudiogramDTO;
    }

    /**
     * 根据-推荐记录id-获取听力档案id-用户的年龄等信息
     */
    @Override
    public HearingAudiogramDTO getInfoByRecommendId(Long id) {
        // 返回对象
        HearingAudiogramDTO hearingAudiogramDTO = new HearingAudiogramDTO();
        try {
            // 根据-推荐记录id-查询听力档案id
            Long hearingArchivesIdById = hearingAudiogramMapper.getHearingArchivesIdById(id);

            // 听力档案id
            hearingAudiogramDTO.setAudiogramId(hearingArchivesIdById);

            // 查询听力档案信息
            HearingAudiogram hearingAudiogram = hearingAudiogramMapper.selectOne(
                    new LambdaQueryWrapper<HearingAudiogram>().eq(HearingAudiogram::getAudiogramId, hearingArchivesIdById));

            // 如果没有找到对应的听力档案信息，直接返回null
            if (hearingAudiogram == null) {
                log.error("没有找到-听力档案 for 听力档案id: {}", hearingArchivesIdById);
                return null;
            }

            // 获取【测前初评】中的，昵称，年龄区间
            HearingInitialValuation hearingInitialValuation = hearingInitialValuationMapper.selectOne(
                    new LambdaQueryWrapper<HearingInitialValuation>()
                            .select(HearingInitialValuation::getNickName, HearingInitialValuation::getAgeRange)
                            .eq(HearingInitialValuation::getInitialValuationId, hearingAudiogram.getInitialValuationId()));
            if (hearingInitialValuation != null) {
                hearingAudiogramDTO.setNickName(hearingInitialValuation.getNickName());
                hearingAudiogramDTO.setAgeRange(hearingInitialValuation.getAgeRange());
            }

            return hearingAudiogramDTO;
        } catch (Exception e) {
            log.error("根据-推荐记录id-获取听力档案id-用户的年龄等信息有误 for 推荐记录id: {}", id, e);
            return null;
        }
    }


}
